package school.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import school.domain.Goods;
import school.domain.Sale;
import school.domain.Shop;
import school.mapper.GoodsMapper;
import school.mapper.SaleMapper;
import school.mapper.ShopMapper;
import school.support.BaseController;
import school.support.pojo.SalePo;
import school.support.util.ParamUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@RequestMapping("sale")
@Controller
public class SaleController extends BaseController {

    @Autowired
    private SaleMapper saleMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 列表
     *
     * @param model
     * @param pageNum
     * @return
     */
    @RequestMapping("list")
    public String list(Model model, @RequestParam(defaultValue = "1") Integer pageNum, SalePo salePo) {
        Example example = new Example(Sale.class);
        Example.Criteria criteria = example.createCriteria();
        if (salePo.getShopname() != null) {
            criteria.andCondition("s.name like ", "%" + salePo.getShopname() + "%");
        }
        if (salePo.getGoodsname() != null) {
            criteria.andCondition("g.name like ", "%" + salePo.getGoodsname() + "%");
        }
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<SalePo> pageInfo = new PageInfo<SalePo>(saleMapper.selectPoByExample(example), 5);
        model.addAttribute(pageInfo);
        model.addAttribute("url", request.getRequestURI() + "?" + ParamUtils.params2String(request));
        return "sale/list";
    }

    @GetMapping("add")
    public String add(Model model) {
        List<Shop> shopList = shopMapper.selectAll();
        model.addAttribute("shopList", shopList);
        return "sale/add";
    }

    @ResponseBody
    @RequestMapping("getByShop")
    public List<Goods> getByPid(Integer shopId) {
        Example example = new Example(Goods.class);
        example.createCriteria().andEqualTo("shopid", shopId);
        return goodsMapper.selectByExample(example);
    }

    @PostMapping("add")
    public String add(Integer goodsId, Integer count, Integer shopId) {
        Sale sale = new Sale();
        sale.setAddtime(new Date());
        sale.setCount(count);
        sale.setGoodsid(goodsId);
        sale.setShopid(shopId);
        saleMapper.insertSelective(sale);
        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        shop.setMoney(shop.getMoney() + goods.getMoney() * count);
        shopMapper.updateByPrimaryKeySelective(shop);
        return "redirect:list";
    }
}
